package run.siyuan.rabbitmq.ttl.message.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import run.siyuan.common.constant.rabbitmq.Constants;

@Slf4j
@RestController
@RequestMapping("/ttl")
public class TtlRabbitmqController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping(value = "/ttl/send")
    public String clearVipInfo(Integer time) {
        log.info("这种方式实现延时队列需要安装插件[{}]","rabbitmq-plugins enable rabbitmq_delayed_message_exchange");
        JSONObject json = new JSONObject();
        json.set("name", "延迟消息");
        json.set("time", System.currentTimeMillis());

        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setExpiration(String.valueOf(1000 * time));
        messageProperties.setHeader("x-delay", 1000 * time);
        Message message = new Message(json.toString().getBytes(), messageProperties);

        String msg = StrUtil.format("延迟消息发送时间：{} 消息数据：{}", System.currentTimeMillis(), json);
        log.info(msg);
        rabbitTemplate.convertAndSend(Constants.Queue.RABBITMQ_TTL_DEMO_EXCHANGE_QUEUE, message);
        log.info("延迟消息发送完成时间：{}", System.currentTimeMillis());
        return "success";
    }

}
